<template>
  <div class="users">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索与添加用户 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
            @blur='getUserList'
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="2">
          <el-button type="primary" @click="isAddDialog = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表去 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <div slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </div>
        </el-table-column>
        <el-table-column label="操作">
          <div slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </div>
        </el-table-column>
      </el-table>

      <!-- 分页表 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户弹出对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="isAddDialog"
        width="50%"
        @close="addDialogClose"
      >
        <el-form
          :model="addRuleForm"
          :rules="addRules"
          ref="addruleFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addRuleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="userPassword">
            <el-input v-model="addRuleForm.userPassword"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="usereEmail">
            <el-input v-model="addRuleForm.usereEmail"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="userPhone">
            <el-input v-model="addRuleForm.userPhone"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isAddDialog = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户信息弹出对话框 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="isEditDialog"
        width="50%"
        @close="editDialogClose"
      >
        <el-form
          ref="editFormRef"
          :model="editForm"
          label-width="70px"
          :rules="editRules"
        >
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isEditDialog = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色对话框 -->
      <el-dialog title="分配角色" :visible.sync="isSetRoleDialog" width="50%" @close='setRoleDialogClose'>
        <p>当前的用户:{{ userInfo.username }}</p>
        <p>当前的角色:{{ userInfo.role_name }}</p>
        <p>
          分配新角色
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isSetRoleDialog = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// 引入获取用户列表的网络请求
import { getUserList } from "../../network/home";
import { userStateChange } from "../../network/home";
import { addUsers } from "../../network/home";
import { getUserInfo } from "../../network/home";
import { editUserInfo } from "../../network/home";
import { deleteUserInfo } from "../../network/home";
import { getRollList } from "../../network/home";
import { saveRoleInfo } from "../../network/home";
export default {
  name: "Users",
  data() {
    // 自定义验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      // 校验邮箱正则表达式
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      // 正则判断
      if (regEmail.test(value)) {
        callback();
      } else callback(new Error("请输入正确的邮箱"));
    };
    // 自定义验证手机号规则
    var checkPhone = (rule, value, callback) => {
      // 校验手机号码的正则表达式
      const regEmail =
        /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
      // 正则判断
      if (regEmail.test(value)) {
        callback();
      } else callback(new Error("请输入正确的手机号码"));
    };
    return {
      // 用户列表信息
      queryInfo: {
        query: "",
        // 当前页数
        pagenum: 1,
        // 当前每页显示条数
        pagesize: 2,
      },
      userList: null,
      //   总共的数据条数
      total: 0,
      // 添加用户
      //   控制添加用户对话框显示与隐藏
      isAddDialog: false,
      //   添加用户的表单数据
      addRuleForm: {
        username: "",
        userPassword: "",
        usereEmail: "",
        userPhone: "",
      },
      //   添加用户的输入框校验规则
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        userPassword: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        usereEmail: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        userPhone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" },
        ],
      },
      //   编辑用户
      // 控制编辑用户对话框显示与影藏
      isEditDialog: false,
      //   编辑用户表单数据
      editForm: {},
      //   编辑用户信息表单校验
      editRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" },
        ],
      },

      // 分配角色
      // 分配角色对话框弹出或影藏
      isSetRoleDialog: false,
      // 需要被分配权限的用户信息
      userInfo: {},
      // 角色列表信息
      rolesList: [],
      // 已选中的角色ID值
      selectedRoleId:'',
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 请求用户列表请求
    async getUserList() {
      const res = await getUserList(this.queryInfo);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 监听pagesize改变  可以获得发送过来的参数
    handleSizeChange(newSize) {
      // 重新赋值
      this.queryInfo.pagesize = newSize;
      //   重新发送请求渲染列表
      this.getUserList();
    },
    // 监听最新的页码值  可以获得发送过来的参数
    handleCurrentChange(newPage) {
      // 重新赋值
      this.queryInfo.pagenum = newPage;
      //   重新发送请求渲染列表
      this.getUserList();
    },
    // 监听开关修改用户状态值
    async userStateChange(data) {
      const url = `/users/${data.id}/state/${data.mg_state}`;
      console.log(url);
      const res = await userStateChange("put", url);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      console.log(res);
    },
    // 监听弹出框的关闭事件
    addDialogClose() {
      this.$refs.addruleFormRef.resetFields();
      this.isAddDialog = false;
    },
    // 添加用户事件
    addUser() {
      this.$refs.addruleFormRef.validate(async (boolean, obj) => {
        // 判断是否校验通过
        if (!boolean) return;
        // 通过之后发起真正的请求请求
        const data = {
          username: this.addRuleForm.username,
          password: this.addRuleForm.userPassword,
          email: this.addRuleForm.usereEmail,
          mobile: this.addRuleForm.userPhone,
        };
        const res = await addUsers("post", data);
        if (res.meta.status != 201) return this.$message.error(res.meta.msg);
        this.getUserList();
        this.isAddDialog = false;
      });
    },
    // 显示修改用户信息对话框
    async showEditDialog(id) {
      const res = await getUserInfo(`users/${id}`);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.editForm = res.data;
      this.isEditDialog = true;
    },
    // 关闭修改用户信息对话框表单重置
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    // 提交修改
    editUserInfo() {
      this.$refs.editFormRef.validate(async (boolean, obj) => {
        // 判断是否校验通过
        if (!boolean) return;
        // 通过之后发起真正的请求请求
        const url = `users/${this.editForm.id}`;
        const data = {
          email: this.editForm.email,
          mobile: this.editForm.mobile,
        };
        const res = await editUserInfo("put", url, data);
        if (res.meta.status != 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.isEditDialog = false;
      });
    },
    // 删除用户 根据用户ID
    async removeUserById(id) {
      // 弹出框警示结果选择触发不同操作
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      //   如果用户取消
      if (confirmResult != "confirm")
        return this.$message.info("已取消删除操作");
      //用户不取消

      const res = await deleteUserInfo("delete", `users/${id}`);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getUserList();
    },
    //分配角色
    // 分配角色按钮点击弹出面板
    async setRole(userInfo) {
      this.userInfo = userInfo;
      // 获取所有角色列表
      const res = await getRollList("get", "roles");
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.rolesList = res.data;
      this.isSetRoleDialog = true;
    },
    //分配新角色
   async saveRoleInfo(){
      if (!this.selectedRoleId) return this.$message.error('请选择用户信息');
     const res= await saveRoleInfo('put',`users/${this.userInfo.id}/role`,this.selectedRoleId)
      if (res.meta.status != 200) return this.$message.error(res.meta.msg)
      this.getUserList()
      this.isSetRoleDialog=false
    },
    //关闭角色设置对话框之后清空资料
    setRoleDialogClose(){
      this.userInfo={},
      this.rolesList=[],
      this.selectedRoleId=''
    }
  },
};
</script>

<style  scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 480px;
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
</style>
